import {
    Injectable,
    NestMiddleware,
    UnauthorizedException,
} from '@nestjs/common';
import { PrismaService } from './prisma/prisma.service';
import { validateToken } from './utils/tool';

@Injectable()
export class ValidateLoginMiddleware implements NestMiddleware {
    constructor(private readonly prisma: PrismaService) { }
    async use(req: any, res: any, next: () => void) {
        // 暂时注释验证部分代码
        // console.log('验证登录');
        // next();
        // console.log(req.cookies?.token);
        // 在cookie和headers同时判断token
        const token = req.cookies?.token || req.headers.token;
        if (token) {
            // console.log(req.cookies.token);
            let user = null;
            let role = null;
            let roleName = null;
            validateToken(token, async (validateResult) => {
                if (validateResult.code) {
                    const { data } = validateResult;
                    user = await this.prisma.user.findFirst({
                        where: {
                            username: data.username
                        }
                    })
                    role = await this.prisma.userRole.findFirst({
                        where: {
                            userId: user.id
                        }
                    })
                    console.log("*********", role)
                    roleName = await this.prisma.role.findFirst({
                        where: {
                            id: role.roleId
                        }
                    })
                    console.log("1111111", roleName)
                    if (req.originalUrl.startsWith('/admin') || req.originalUrl.startsWith('/user')) {
                        if (roleName.name !== "管理员") {
                            return res.status(401).json({
                                code: 401,
                                message: "没有权限"
                            })
                        }
                    }
                }
                next();
            });
        } else {
            throw new UnauthorizedException();
        }
    }
}
